package com.take.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.take.common.BaseContext;
import com.take.common.R;
import com.take.utils.JwtTokenUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    @Autowired
    JwtTokenUtils jwtTokenUtils;
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("UTF-8");

        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();// /backend/index.html

        log.info("拦截到请求：{}", requestURI);

        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/doc.html#/**",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
//                "/category/**",
//                "/dish/**",
//                "/setmeal/**",

        };

        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if (check) {
            log.info("本次请求{}不需要处理，直接放行！", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //获取token
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("Authorization");
        //判断token是否存在
        if (!StringUtils.hasLength(token)) {
            R error = R.error("未登录，本次请求被拦截！");
            String noLogin = JSONObject.toJSONString(error);
            response.setStatus(401);
            response.getWriter().write(noLogin);
            return;
        }
        //解析token是否存在
        try {
            //解析token是否合法
            Claims claims = jwtTokenUtils.parseJwt(token);
            //获得用户的信息，判断是employee? 还是 user?
            // claims.get("id")是Object
            // Map<String，Object> 由于我们使用 Object 类型来接收数字，map并不知道我们传入的是 Long 还是 Integer 。
            // 所以 Map 会根据我们传入的数值的大小来判断。
            //也就是说如果你传入的数值的大小是在 Integer.MIN_VALUE、 Integer.MAX_VALUE 之间，Map 就认为是 Integer 类型，
            // 如果超过了这个范围就认为是 Long 类型。
            // https://blog.csdn.net/showadwalker/article/details/122496963
            Long empId = Long.valueOf(String.valueOf(claims.get("id")));
            BaseContext.setCurrentId(empId);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("用户登录已失效");
            response.setCharacterEncoding("utf-8");
            response.setStatus(401);
            response.getWriter().write(JSON.toJSONString(R.error("员工用户未登录")));
            return;
        }
        log.info("令牌合法，放行:{}", token);
        filterChain.doFilter(request, response);


        //4-1、判断登录状态，如果已登录，则直接放行
        //        if(request.getSession().getAttribute("employee") != null){
        //            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
        //
        //            Long empId = (Long) request.getSession().getAttribute("employee");
        //            BaseContext.setCurrentId(empId);
        //
        //            filterChain.doFilter(request,response);
        //            return;
        //        }

        //4-2、判断登录状态，如果已登录，则直接放行
        //        if(request.getSession().getAttribute("user") != null){
        //            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
        //
        //            Long userId = (Long) request.getSession().getAttribute("user");
        //            BaseContext.setCurrentId(userId);
        //
        //            filterChain.doFilter(request,response);
        //            return;
        //        }

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
